package admin_service

import (
	"github.com/cihub/seelog"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/result"
)

type GoodsDto struct { // 方便连表查询
	entity.Goods
	GoodsCategoryName string `json:"goodsCategoryName" gorm:"goods_category_name"`
}

func GetGoodsList(shopId int) *result.Result {
	goodsList := make([]*GoodsDto, 0, 0)
	dao.GetDB().Table(entity.TableNameGoods).Select(`goods.id,goods.shop_id,goods.goods_category_id,goods.name,goods.display_order,
			goods.price,goods.count,goods.status,goods.image,goods.property_list,goods.description,
			goods_category.name as goods_category_name`).
		Joins("left join goods_category on goods_category.id=goods.goods_category_id").
		Where("goods.shop_id", shopId).Scan(&goodsList)
	for _, goods := range goodsList {
		goods.ParsePropertyList()
	}
	return result.Ok(goodsList)
}

func AddGoods(shopId int, goods *entity.Goods) *result.Result {
	goods.ShopId = shopId
	goods.Status = constant.GoodsStatusOnSell
	goods.PropertyListToStr()
	rows := dao.GetTx().Model(goods).Create(goods).Commit().RowsAffected
	return result.Ok(rows)
}

func UpdateGoods(goodsId int64, shopId int, goods *entity.GoodsFilter) *result.Result {
	goods.PropertyListToStr()
	rows := dao.GetTx().Model(goods).Where("id=? and shop_id=?", goodsId, shopId).Updates(goods).Commit().RowsAffected
	return result.Ok(rows)
}

func UpdateGoodsImg(goodsId int, url string) *result.Result {
	err := dao.GetTx().Table(entity.TableNameGoods).Where("id", goodsId).UpdateColumn("image", url).Commit().Error
	if err != nil {
		seelog.Errorf("更新数据库失败，err: %v", err)
		return result.Fail("图片更新失败")
	}
	return result.Ok(url)
}

func DeleteGoods(goodsId int64, shopId int) *result.Result {
	rows := dao.GetTx().Where("id=? and shop_id=?", goodsId, shopId).Delete(nil).Commit().RowsAffected
	return result.Ok(rows)
}
